import { defineStore } from 'pinia'
import piniaPersistConfig from '../persist'

export interface CacheItem<T = any> {
  data: T
  timestamp: number
  expireTime: number
  key: string
}

export interface AdvancedCacheState {
  caches: Record<string, CacheItem>
  defaultExpireTime: number
}

export const useAdvancedCacheStore = defineStore('advancedCache', {
  state: (): AdvancedCacheState => ({
    caches: {},
    defaultExpireTime: 60 * 60 * 1000, // 5分钟默认过期时间
  }),

  getters: {
    // 检查缓存是否有效
    isCacheValid: (state) => (key: string) => {
      const cache = state.caches[key]
      if (!cache) return false
      const now = Date.now()
      return (now - cache.timestamp) < cache.expireTime
    },

    // 获取缓存数据
    getCacheData: (state) => (key: string) => {
      const cache = state.caches[key]
      return cache ? cache.data : null
    }
  },

  actions: {
    // 设置缓存
    setCache<T>(key: string, data: T, expireTime?: number) {
      this.caches[key] = {
        data,
        timestamp: Date.now(),
        expireTime: expireTime || this.defaultExpireTime,
        key
      }
    },

    // 获取缓存（带有效性检查）
    getCache<T>(key: string): T | null {
      if (this.isCacheValid(key)) {
        return this.getCacheData(key) as T
      }
      return null
    },

    // 清除指定缓存
    clearCache(key: string) {
      delete this.caches[key]
    },

    // 清除所有缓存
    clearAllCache() {
      this.caches = {}
    },

    // 清除过期缓存
    clearExpiredCache() {
      const now = Date.now()
      Object.keys(this.caches).forEach(key => {
        const cache = this.caches[key]
        if ((now - cache.timestamp) >= cache.expireTime) {
          delete this.caches[key]
        }
      })
    },

    // 生成缓存键
    generateCacheKey(prefix: string, params: Record<string, any>): string {
      const sortedParams = Object.keys(params)
        .sort()
        .map(key => `${key}=${params[key]}`)
        .join('&')
      return `${prefix}:${sortedParams}`
    },

    // 预热缓存
    async warmupCache<T>(
      key: string, 
      fetchFn: () => Promise<T>, 
      expireTime?: number
    ): Promise<T> {
      // 先检查缓存
      const cached = this.getCache<T>(key)
      if (cached) {
        return cached
      }

      // 缓存未命中，获取数据并缓存
      try {
        const data = await fetchFn()
        this.setCache(key, data, expireTime)
        return data
      } catch (error) {
        // 获取失败时，尝试返回过期缓存作为降级
        const expiredCache = this.caches[key]
        if (expiredCache) {
          console.warn(`使用过期缓存作为降级: ${key}`)
          return expiredCache.data as T
        }
        throw error
      }
    }
  },

  persist: piniaPersistConfig('advancedCache')
})
